package cn.wolfcode.trip.admin.filter;

import cn.wolfcode.trip.admin.qiniu.SevenUploadUtil;
import cn.wolfcode.trip.admin.util.UploadUtil;
import org.apache.commons.io.FileUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

public class ImageFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    //图片过滤
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //从请求中获取访问图片路径
        HttpServletRequest req = (HttpServletRequest) request;
        //拿到/upload/xxx.jpg,相当于数据库中图片的全名,包括拓展名
        String imageUrl = req.getRequestURI();
        //2.判断上面imageUrl是否在共享空间中,将文件名和前缀拼接起来
        File file = new File(SevenUploadUtil.domainName+imageUrl);
        if(file.exists()){
            //图片存在,相当于图片下载操作
            //从硬盘中读取图片
            byte[] bytes = FileUtils.readFileToByteArray(file);
            //将图片响应给浏览器
            response.getOutputStream().write(bytes);
        }else {
            //图片不存在,不用管,直接放行
            chain.doFilter(request,response);
        }

    }


    public void destroy() {

    }
}
